package websocket2

import (
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"spirit/utils"
	"time"
)

var upGrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
	return true
}}
var wsMap = utils.NewSpiritMap()

type Handler func(*Connection)

func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var (
		wsConn *websocket.Conn
		err    error
		conn   *Connection
	)
	if wsConn, err = upGrader.Upgrade(w, req, nil); err != nil {
		return
	}

	if conn, err = InitConnection(wsConn, true, nil); err != nil {
		goto ERR
	} else {
		////要求客户端发送ClientId
		conn.WriteMessage(EnPacket(ActRequestClientId, []byte{}))
		time.Sleep(1 * time.Second)
		h(conn)
	}

ERR:
	//TODO :关闭连接
	conn.Close()

}

func join(id string, conn *Connection) {
	c := wsMap.Get(id)
	if c != nil {
		(c.(*websocket.Conn)).Close()
	}
	if b := wsMap.Set(id, conn); b {
		log.Printf("client:[%s] connected successful", id)
	}
}

func CheckHeartbeat() {
	now := time.Now().Unix()
	for _, v := range wsMap.Map {
		conn := v.(*Connection)
		if now-conn.timestamp < 60 {
			//log.Printf("向客户端[%s]发送心跳请求包:[%d]", k, now)
			conn.WriteMessage(EnPacket(ActRequestHeartBeat, int2byte(int(now))))
		} else {
			wsMap.Delete(conn.clientId)
			conn.Close()
			log.Printf("检测到客户端[%s]超时,主动断开连接", conn.clientId)
		}

	}
	time.AfterFunc(5*time.Second, CheckHeartbeat)
}

func OnlineConnection() *utils.SpiritMap {
	return wsMap
}
